﻿#region

using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using InfoTech.VinhSon.Bussiness;
using VinhSon.Models;

#endregion

namespace VinhSon.Controllers
{
    public class AccountController : Controller
    {
        protected UnitOfWork UnitOfWork = new UnitOfWork();

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model,
                                  string returnUrl)
        {
            if(ModelState.IsValid)
            {
                User user = UnitOfWork.UserRepository.Select(c => c.Username == model.UserName && c.Password == model.Password)
                                      .FirstOrDefault();
                if(user != null)
                    if(false == user.Inactive
                       || null == user.Inactive)
                        if(user.Activated == true)
                        {
                            Session["UserId"] = user.Id;
                            FormsAuthentication.SetAuthCookie(model.UserName,
                                                              model.RememberMe);
                            if(Url.IsLocalUrl(returnUrl)
                               && returnUrl.Length > 1
                               && returnUrl.StartsWith("/")
                               && !returnUrl.StartsWith("//")
                               && !returnUrl.StartsWith("/\\"))
                            {
                                return Redirect(returnUrl);
                            }
                            return RedirectToAction("Index",
                                                    "Dashboard",
                                                    new
                                                        {
                                                                area = "Administrator"
                                                        });
                        }
                ModelState.AddModelError("",
                                         "The user name or password provided is incorrect.");
            }
            return View(model);
        }
    }
}
